import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import DataType.MessageFormat;

public class VirtualSensor extends Thread {

	protected VSensorConfig config;
	protected long lastModified;
	private static int threadID = 0;
	protected SocketSender sender;
	private Thread thread;

	public static String nowTime() {
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(new Date().getTime());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss:SSS");
		return dateFormat.format(c.getTime());
	}

	public VSensorConfig getConfig() {
		return config;
	}

	public VirtualSensor(VSensorConfig config, SocketSender sender) {
		this.config = config;
		this.lastModified = new File(config.getFileName()).lastModified();
		this.sender = sender;
	}
	
	public boolean isLive() {
		
		return thread.isAlive();
	}

	public void startThread() {
		thread = new Thread(this);
		thread.setName(config.getName() + threadID++);
		thread.start(); // start this thread
	}

	public void close() {
		System.out.println("Thread is closed!");
		thread.interrupt();
	}

	protected String prepareJsonStr() {
		return "";
	}

	public long getLastModified() {
		return this.lastModified;
	}

	public String getLastModifiedTime() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyy/MM/dd HH:mm:ss:SSS");
		String lastMofiedTime = sdf.format(lastModified);
		return lastMofiedTime;
	}

	protected ByteBuffer prepareData() {
		int headerLen = MessageFormat.packetHeaderLen;
		String jsonStr = prepareJsonStr();
		try {
			JSONObject jsonObj = new JSONObject(jsonStr);
			byte[] jsonBytes = jsonObj.toString().getBytes(
					MessageFormat.encoding);
			short packetLen = (short) (headerLen + jsonBytes.length);
			ByteBuffer bb = ByteBuffer.wrap(new byte[packetLen]);
			bb.order(MessageFormat.byteOrder);
			bb.put(MessageFormat.hexStringToByteArray("0x004345544300"));
			bb.put(MessageFormat.hexStringToByteArray("0x0001000B"));
			bb.putInt(config.getGatewayId());
			System.out.println("Gateway id = " + config.getGatewayId());
			System.out.println("jsonStr = " + jsonStr);
			bb.putShort((short) jsonBytes.length);
			bb.put(jsonBytes);
			return bb;
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

}
